<template>
  <div class="websocket"></div>
</template>
<script>
export default {
  name: 'Websocket',
  props: {
    // 接入socketKey值
    socketKey: {
      type: String,
      default: ''
    },
    // 接口
    apiInfo: {
      type: String,
      default: ''
    },
    // 参数
    params: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      localhost: '127.0.0.1:5255',
      userId: 'userId',
      lockReconnect: false, // 连接失败不进行重连
      maxReconnect: 3, // 最大重连次数，若连接失败
      socket: null,
      timeout: 5 * 1000, // 再次重连的时间
      timer: null,
      serverTimer: null
    }
  },
  mounted() {
    this.initWebSocket()
  },
  beforeDestroy() {
    this.timer && clearTimeout(this.timer)
    this.serverTimer && clearTimeout(this.serverTimer)
  },
  destroyed() {
    this.socket.close()
  },
  methods: {
    heartCheck(ws) {
      this.timer && clearTimeout(this.timer)
      this.serverTimer && clearTimeout(this.serverTimer)
      this.timer = setTimeout(() => {
        console.log('发送心跳,后端收到后，返回一个心跳消息')
        // onmessage拿到返回的心跳就说明连接正常
        ws.send(JSON.stringify({ heart: 1 }))
        // this.serverTimer = setTimeout(() => {
        //   // 如果超过一定时间还没响应(响应后触发重置)，说明后端断开了
        //   ws.close()
        // }, this.timeout)
      }, this.timeout)
    },
    // websoket方法
    reconnect() {
      console.log('尝试重连')
      console.log(this.maxReconnect)
      if (this.lockReconnect || this.maxReconnect <= 0) {
        return
      }
      setTimeout(() => {
        this.maxReconnect-- // 做限制 连不上3次不重连
        this.initWebSocket()
      }, this.timeout)
    },
    initWebSocket() {
      this.timer && clearTimeout(this.timer)
      this.serverTimer && clearTimeout(this.serverTimer)

      let wsuri = `ws://${this.localhost}/websocket?socketKey=${this.socketKey}&userId=${this.userId}&apiInfo={'api':'${this.apiInfo}','params':${JSON.stringify(this.params)}}`

      console.log('---wsuri---')
      console.log(wsuri)

      try {
        if ('WebSocket' in window) {
          this.socket = new WebSocket(wsuri)
        } else {
          console.log('您的浏览器不支持websocket')
        }
        this.socket.onopen = this.websocketonopen
        this.socket.onerror = this.websocketonerror
        this.socket.onmessage = this.websocketonmessage
        this.socket.onclose = this.websocketclose
      } catch (e) {
        this.reconnect()
      }
    },
    websocketonopen() {
      console.log('WebSocket连接成功', this.socket.readyState)
      this.heartCheck(this.socket)
      this.socket.send('发送数据')
      this.websocketsend()
    },
    websocketonerror(e) {
      console.log('WebSocket连接发生错误', e)
      this.reconnect()
    },
    websocketonmessage(e) {
      let data = JSON.parse(e.data)
      // 发送出PM10的实时数据 和 发送出环境监测告警表格 实时数据
      // if (data.dataType === 'realTimeData' || data.dataType === 'warnData') {
      // 调用成功
      this.$emit('websocketSuccess', data)
      // }

      // 消息获取成功，重置心跳
      this.heartCheck(this.socket)
    },
    websocketclose(e) {
      // console.log('connection closed (' + e.code + ')')
      // this.reconnect()
    },
    websocketsend() {
      let data = { text: '我是前端连接成功' }
      this.socket.send(JSON.stringify(data))
    }
  }
}
</script>
<style lang="scss" scoped>
.websocket {
  display: none;
}
</style>
